<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <title>部门管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
    <link rel="stylesheet" th:href="@{/css/admin/city-select.css}">

    <style>
        .popup-default > .body, .popup-default > .section {
            background: #fff;
            border-radius: 5px;
            border: 1px solid #e6e6e6;
            min-width: 600px;
        }

        .city-select .city-info {
            border: 1px solid #e6e6e6;
            background-color: #fff;
            cursor: pointer;
            width: 464px;
            border-radius: 5px;
            overflow: hidden;
            padding: 3px 10px;
            padding-top: 0;
            position: relative;
            z-index: 2;
        }

        .popup-default .content {
            padding: 20px;
            max-height: 400px;
            overflow: visible;
        }

        .city-select .city-input em {
            color: #777;
            display: block;
            font-style: inherit;
            font-size: 14px;
            height: 24px;
            line-height: 24px;
            letter-spacing: 1px;
        }

        .city-select .city-pavilion {
            box-shadow: 0 0px 0px #eee;
            width: 464px;
        }

        .city-select {
            font-size: 0;
            position: relative;
            display: inline-block;
            z-index: 2;
        }
    </style>

</head>

<body>

<div class="app-page">

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>状态</label></div>
                                    <div class="flex1">
                                        <select name="status" id="">
                                            <option value="">全部</option>
                                            <option value="0">启用</option>
                                            <option value="1">禁用</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>部门名称</label></div>
                                    <div class="flex1">
                                        <input type="text" placeholder="部门名称" name="departmentName">
                                    </div>
                                </div>
                            </div>
                            <div style="display: none">
                                <input name="pageNum" th:value="${pageNum}">
                                <input name="pageSize" th:value="${pageSize}">
                            </div>
                            <div class="filter-item">
                                <button class="z-btn z-primary">查询</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">

                    <div class="z-btn-group">
                        <a data-title="创建部门" class="j-btn-control z-btn z-default btn-add">创建部门</a>
                        <a data-title="批量启用" class="j-btn-control z-btn z-default btn-batch-able">批量启用</a>
                        <a data-title="批量禁用" class="j-btn-control z-btn z-default btn-batch-disable">批量禁用</a>
                    </div>

                    <table class="z-table">
                        <thead>
                        <tr>
                            <th>
                                <input type="checkbox" class="input j-checkbox-all">
                            </th>
                            <th>部门名称</th>
                            <th>部门代码</th>
                            <!--<th>上级部门</th>-->
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr th:each="department: ${departmentList}" th:attr="data-id=${department.departmentId}, data-departmentname=${department.departmentName},
                        data-departmentcode=${department.departmentCode},data-status=${department.status}">
                            <td>
                                <input type="checkbox" class="input j-checkbox">
                            </td>
                            <td th:text="${department.departmentName}"></td>
                            <td th:text="${department.departmentCode}"></td>
                            <!--注释上级部门，以后需要，再启用-->
                            <!--<td th:text="${department.parentDepartmentName}"></td>-->
                            <div th:switch="${department.status}">
                                <td th:case="1">禁用</td>
                                <td th:case="0">启用</td>
                            </div>
                            <td class="btn-group" th:switch="${department.status}">
                                <a class="btn-enable" th:case="1">启用</a>
                                <a class="btn-disable" th:case="0">禁用</a>
                                <a class="btn-detail">修改</a>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                    <!-- 分页 -->
                    <div class="app-card-body">
                        <div class="pagination z-pat z-fr"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<!--新增/编辑-->
<div class=" popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close=""></div>

    <!--新增-->
    <div class="section popup-add z-hide">
        <div class="title">创建部门</div>
        <div class="content" id="departmentForm">
            <form>
                <div class="form-item row" style="display: none">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="hidden" name="departmentId" class="departmentId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门名称</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门名称" class="departmentName"
                               name="departmentName" data-name="部门名称" data-rule="required,length" minlength="1"
                               maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门代码</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门代码" class="departmentCode" name="departmentCode"
                               data-name="部门代码" data-rule="length" maxlength="32">

                    </div>
                </div>
                <!--注释上级部门，以后需要，再启用-->
                <!--<div class="form-item row">
                    <div class="label">
                        <label>上级部门</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="parentId z-hide parentId" name="parentId">
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="parentName" name="parentName">
                            <span class="input-group-addon select-parent"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>-->

                <div class="form-item row">
                    <div class="label">
                        <label>选择城市</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="z-hide cityCodes" name="cityCodes">
                        <input type="hidden" name="cityNames">

                        <!-- 城市选择插件结构 -->
                        <div class="city-select" id="multi-select"></div>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>状态</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="1" th:text="禁用"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="0" th:text="启用"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close="">取消</a>
            </div>
        </div>
    </div>

    <!--编辑-->
    <div class="popup-detail section z-hide">
        <div class="title">修改部门</div>
        <div class="content">
            <form>
                <div class="form-item row" style="display: none">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="hidden" name="departmentId" class="departmentId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门名称</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门名称" class="departmentName"
                               name="departmentName" data-name="部门名称" data-rule="required,length" minlength="1"
                               maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门代码</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门代码" class="departmentCode" name="departmentCode"
                               data-name="部门代码" data-rule="length" maxlength="32">

                    </div>
                </div>
                <!--注释上级部门，以后需要，再启用-->
                <!--<div class="form-item row">
                    <div class="label">
                        <label>上级部门</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="parentId z-hide parentId" name="parentId">
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="parentName" name="parentName">
                            <span class="input-group-addon select-parent"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>-->

                <div class="form-item row">
                    <div class="label">
                        <label>选择城市</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="z-hide cityCodes" name="cityCodes">
                        <input type="hidden" name="cityNames">

                        <!-- 城市选择插件结构 -->
                        <div class="city-select" id="edit-multi-select"></div>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>状态</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="1" th:text="禁用"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="0" th:text="启用"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close="">取消</a>
            </div>
        </div>

    </div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script th:src="@{/js/citydata.min.js}"></script>
<script th:src="@{/js/citySelect-1.0.3.js}"></script>
<script type="text/javascript" th:inline="javascript">
    //获取context path
    var context = $("meta[name='ctx']").attr("content") || '';

    var EditMulticitySelect;
    var MulticitySelect;

    $(function () {

        var cityData = [];
        var url = "/area/listTree";
        if (context) {
            url = context + url;
        }
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    cityData = obj.data;
                }
                initCityData();
            }
        })

        eventEmit();
    })


    function initCityData() {
        // 设置接口
        MulticitySelect = $('#multi-select').citySelect({

            // 数据接口
            dataJson: cityData,

            // 多选
            multiSelect: true,

            // 多选个数
            multiMaximum: 6,

            // 开启搜索
            search: false,

            // 显示行数
            multiType: 0,

            // 插件初始化后的回调
            onInit: function () {
                console.log(this)
            },

            // 选择城市后的回调
            onCallerAfter: function (target, values) {
                console.log(JSON.stringify(values))
            },

        });

        EditMulticitySelect = $('#edit-multi-select').citySelect({

            // 数据接口
            dataJson: cityData,

            // 多选
            multiSelect: true,

            // 多选个数
            multiMaximum: 6,

            // 开启搜索
            search: false,

            // 显示行数
            multiType: 0,

            // 插件初始化后的回调
            onInit: function () {
                console.log(this)
            },

            // 选择城市后的回调
            onCallerAfter: function (target, values) {
                console.log(JSON.stringify(values))
            },

        });
    }

    var departmentid = null;
    //部门关联城市列表
    var departmentCity = null;
    // 禁用的城市
    var departmentCityDisabled = null;

    function eventEmit() {
        // 新增 - 弹窗打开
        $('.btn-add').click(function () {
            MulticitySelect.clear();
            departmentCity = null;
            departmentCityDisabled = null;
            $('.popup-add').formLoad({
                departmentId: '',
                departmentName: '',
                departmentCode: '',
                parentName: '',
                status: 0,
            })
            popup.open('.popup-add')
        })

        // 修改 - 弹窗打开
        $('.btn-detail').click(function () {

            EditMulticitySelect.clear();

            var data = $(this).parents('tr')[0].dataset;
            //取值
            departmentid = data["id"];
            var departmentname = data["departmentname"];
            var departmentcode = data["departmentcode"];
            var parentdepartmentname = data["parentdepartmentname"];
            var status = data["status"];

            $('.popup-detail').formLoad({
                departmentId: departmentid,
                departmentName: departmentname,
                departmentCode: departmentcode,
                parentName: parentdepartmentname,
                status: status,
            })
            //获取部门管理的城市
            var departmentUrl = "/area/listCityByDeparmentId";
            if (context) {
                departmentUrl = context + departmentUrl;
            }
            if (departmentid) {
                departmentUrl = departmentUrl + "?departmentId=" + departmentid;
            }
            App.ajax({
                type: "POST",
                url: departmentUrl,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        var names = [];
                        var codes = [];
                        for (var i = 0; i < obj.data.length; i++) {
                            var item = obj.data[i];
                            var name = item["name"];
                            var code = item["code"];

                            names.push(name);
                            codes.push(code);
                        }

                        var namesStr = names.join(',');
                        var codesStr = codes.join(",");

                        EditMulticitySelect.setCityVal(namesStr);

                        $('.popup-detail input[name=cityCodes]').val(codesStr);
                        $('.popup-detail input[name=cityNames]').val(namesStr);
                        $('.popup-detail input[name=cityNames1]').val(namesStr);
                    }
                }
            })
            popup.open('.popup-detail');
        })

        // var url = "/department/goDepartmentPickerPage"
        // if (context) {
        //     url = context + url;
        // }
        // // 选择父级部门
        // $(document).on('click', '.select-parent', function () {
        //     layer.open({
        //         type: 2 //此处以iframe举例
        //         , title: '选择父部门'
        //         , area: ['900px', '500px']
        //         , maxmin: true
        //         , content: url
        //         , btn: ['确定', '取消'] //只是为了演示
        //         , btnAlign: 'c'
        //         , yes: function (index, layero) {
        //             // 获取layer中的数据
        //             var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法
        //             // 用iframeWin.functionname() 调用窗口中的方法
        //             // var data = iframeWin.getData()
        //             var data = iframeWin.getTreeData();
        //
        //             if (data) {
        //                 $('input[name=parentName]').val(data.namedata);
        //                 $('input[name=parentId]').val(data.idsdata);
        //                 layer.close(index) //如果有数据，需进行手工关闭
        //             }
        //         }
        //         , btn2: function (index, layero) {
        //             layer.closeAll()
        //         }
        //
        //         , zIndex: layer.zIndex //重点1
        //         , success: function (layero) {
        //             layer.setTop(layero) //重点2
        //         }
        //     })
        //
        // })

        // //获取部门关联的城市和已被选择的城市
        // $(document).on('click', '.select-city', function () {
        //     //选择城市
        //     var cityUrl = "/department/goSelectCity";
        //     if (context) {
        //         cityUrl = context + cityUrl;
        //     }
        //     if (departmentCity) {
        //         cityUrl = cityUrl + "?city=" + encodeURIComponent(JSON.stringify(departmentCity)) + "&disabled=" + encodeURIComponent(JSON.stringify(departmentCityDisabled));
        //         console.log("cityUrl :", departmentCity);
        //     }
        //     layer.open({
        //         type: 2 //此处以iframe举例
        //         , title: '选择城市'
        //         , area: ['900px', '500px']
        //         , maxmin: true
        //         , content: cityUrl
        //         , btn: ['确定', '取消'] //只是为了演示
        //         , btnAlign: 'c'
        //         , yes: function (index, layero) {
        //             // 获取layer中的数据
        //             var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法
        //             // 用iframeWin.functionname() 调用窗口中的方法
        //             // var data = iframeWin.getData()
        //             var data = iframeWin.getSelectCity();
        //             var names = [];
        //             var codes = [];
        //
        //             var newDepartmentCity = []
        //             for (var i = 0; i < data.length; i++) {
        //                 var item = data[i];
        //                 var name = item["name"];
        //                 var code = item["code"];
        //
        //                 names.push(name);
        //                 codes.push(code);
        //
        //                 newDepartmentCity.push({
        //                     name: name,
        //                     code: code,
        //                 })
        //             }
        //
        //             departmentCity = newDepartmentCity;
        //
        //             names.join(',');
        //             codes.join(",");
        //
        //             if (data) {
        //                 if (!$('.popup-add').hasClass('z-hide')) {
        //                     $('.popup-add input[name=cityCodes]').val(codes);
        //                     $('.popup-add input[name=cityNames]').val(names);
        //                     $('.popup-add input[name=cityNames1]').val(names);
        //                 } else {
        //                     $('.popup-detail input[name=cityCodes]').val(codes);
        //                     $('.popup-detail input[name=cityNames]').val(names);
        //                     $('.popup-detail input[name=cityNames1]').val(names);
        //                 }
        //
        //                 layer.close(index) //如果有数据，需进行手工关闭
        //             }
        //         }
        //         , btn2: function (index, layero) {
        //             layer.closeAll()
        //         }
        //         , zIndex: layer.zIndex //重点1
        //         , success: function (layero) {
        //             layer.setTop(layero) //重点2
        //         }
        //     })
        // })
    }

    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    //处理分页
    var pageNum = [[${pageNum}]];
    var pageSize = [[${pageSize}]];
    var total = [[${total}]];
    var pagination = new Pagination(".pagination", {
        pageIndex: pageNum, // 当前页数
        pageSize: pageSize, // 每页数量
        count: total, // 总条数
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function (pageIndex) {
            window.location.href = context + "/department/list?pageNum=" + pageIndex + "&pageSize=" + pageSize;
        }
    })


    // 新增 - 弹窗保存
    var form = $(".popup-add form").form({
        submitSelector: ".popup-add .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-add form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })

            var citys = MulticitySelect.getCityVal();
            if (!isBlank(citys)) {
                data['cityCodes'] = isBlank(citys.id) ? '' : citys.id.join(',');
                data['cityNames'] = isBlank(citys.name) ? '' : citys.name.join(',');
            } else {
                data['cityCodes'] = '';
                data['cityNames'] = '';
            }

            console.log(data);
            App.ajax({
                type: "POST",
                url: context + "/department/save",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('创建部门成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/department/list";
                        }, 100);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })


    // 修改 - 弹窗确定
    var form = $(".popup-detail form").form({
        submitSelector: ".popup-detail .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {

            var data = {};
            $.each($(".popup-detail form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })

            var citys = EditMulticitySelect.getCityVal();

            if (!isBlank(citys)) {
                data['cityCodes'] = isBlank(citys.id) ? '' : citys.id.join(',');
                data['cityNames'] = isBlank(citys.name) ? '' : citys.name.join(',');
            } else {
                data['cityCodes'] = '';
                data['cityNames'] = '';
            }
            console.log(data);
            //修改
            App.ajax({
                type: "POST",
                url: context + "/department/update",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('修改部门成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/department/list";
                        }, 1000);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 启用/禁用
    $('.btn-disable,.btn-enable').click(function () {
        var data = $(this).parents('tr')[0].dataset;
        var id = data["id"];
        //默认（0：启用）
        var status = 0;
        if ($(this).hasClass('btn-enable')) {
            App.ajax({
                type: "POST",
                url: context + "/department/enableDisableDepartment",
                data: {
                    departmentId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('enable', '启用部门成功');
                        //跳转到用户列表
                        window.location.href = context + "/department/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        } else {
            //禁用
            status = 1;
            App.ajax({
                type: "POST",
                url: context + "/department/enableDisableDepartment",
                data: {
                    departmentId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('disable', '禁用部门成功');
                        //跳转到用户列表
                        window.location.href = context + "/department/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 批量启用禁用部门
    $('.btn-batch-able, .btn-batch-disable').click(function () {
        var status = 0;
        var optName = "批量启用";
        if ($(this).hasClass('btn-batch-disable')) {
            status = 1;
            optName = "批量禁用";
        }

        let idArr = [];
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                var id = $(this).parents('tr,.tr').data('id');
                idArr.push(id);
            }
        })
        var ids = idArr.join(',');
        if (isBlank(ids)) {
            popup.tipsTop('请选择需要' + optName + '的部门', 'warning');
            return;
        }
        App.ajax({
            type: "POST",
            url: context + "/department/batchAbleDisable",
            data: {
                ids: ids,
                status: status
            },
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    popup.tipsTop((optName + '成功'), 'success');
                    setTimeout(function () {
                        //跳转到部门列表
                        window.location.href = context + "/department/list";
                    }, 1000);
                } else {
                    popup.tipsTop(obj.msg, 'warning');
                }
            }
        })
    })

    //检查参数
    function isBlank(param) {
        if (undefined === param) {
            return true;
        }
        if (null == param) {
            return true;
        }
        if ("" === param) {
            return true;
        }
        return false;
    }
</script>
</body>

</html>